package com.dangf.launcher.server.service

import android.app.Service
import android.content.Intent
import android.os.Environment
import android.os.IBinder
import com.dangf.launcher.server.app.V
import com.dangf.launcher.server.httpserver.DFStorageWebsite
import com.dangf.launcher.server.httpserver.response.RequestApiHandler
import com.dangf.launcher.server.httpserver.response.RequestFileHandler
import com.yanzhenjie.andserver.AndServer
import com.yanzhenjie.andserver.Server
import java.io.File
import java.lang.Exception

/**
 * Created by hais1992 on 2017/9/29.
 */
class HttpService : Service(), Server.Listener {
    private val TAG = "HTTP服务"
    private var httpServer: Server? = null
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        initHttpServer()
    }

    override fun onDestroy() {
        super.onDestroy()
        httpServer?.stop()
    }


    private fun initHttpServer() {
        V.printLog(TAG, "正在初始化")
        val andServer = AndServer.Build().port(V.HTTP_SERVER_PORT).timeout(10 * 1000)
                .registerHandler("/api", RequestApiHandler())
                .registerHandler("/file", RequestFileHandler())
                .website(DFStorageWebsite(File(Environment.getExternalStorageDirectory(), V.DATA_PATH).absolutePath))
                .listener(this)
                .build()
        httpServer = andServer?.createServer()
        httpServer?.start()
    }

    override fun onStarted() {
        V.printLog(TAG, "启动成功,开始监听 ${V.HTTP_SERVER_IP}:${V.HTTP_SERVER_PORT}")
    }

    override fun onError(e: Exception?) {
        V.printLog(TAG, "发生异常->$e")
    }

    override fun onStopped() {
        V.printLog(TAG, "停止运行")
    }
}